package com.bite.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bite.storage.entity.StorageInfo;
import com.bite.storage.mapper.StorageMapper;
import com.bite.storage.service.StorageTccService;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import io.seata.rm.tcc.api.LocalTCC;
import io.seata.rm.tcc.api.TwoPhaseBusinessAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@LocalTCC
public class StorageTccServiceImpl implements StorageTccService {
    @Autowired
    private StorageMapper storageMapper;

    @Override
    @TwoPhaseBusinessAction(name = "storageDeduct", commitMethod = "commit",
            rollbackMethod = "rollback", useTCCFence = true)
    public boolean prepare(@BusinessActionContextParameter("commodityCode") String commodityCode,
                           @BusinessActionContextParameter("count") Integer count) {
        log.info("一阶段try...");
        try {
            UpdateWrapper<StorageInfo> updateWrapper = new UpdateWrapper<>();
            updateWrapper.lambda().setSql("count = count - "+ count)
                    .setSql("freeze_count = freeze_count + " + count )
                    .eq(StorageInfo::getCommodityCode, commodityCode);
            storageMapper.update(updateWrapper);
            int a = 10/0;
            return true;
        } catch (Exception e) {
            log.error("扣减库存失败, e:", e);
            throw new RuntimeException("扣减库存失败!", e);
        }
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        log.info("二阶段commit...");
        //进行库存的扣减(冻结库存)
        String commodityCode = (String)actionContext.getActionContext("commodityCode");
        Integer count = (Integer) actionContext.getActionContext("count");

        UpdateWrapper<StorageInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().setSql("freeze_count = freeze_count - " + count)
                .eq(StorageInfo::getCommodityCode, commodityCode);
        Integer result =  storageMapper.update(updateWrapper);

        return result==1;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        log.info("二阶段rollback...");
        //进行库存的扣减(冻结库存)
        String commodityCode = (String)actionContext.getActionContext("commodityCode");
        Integer count = (Integer) actionContext.getActionContext("count");

        UpdateWrapper<StorageInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().setSql("count = count + "+ count)
                .setSql("freeze_count = freeze_count - " + count)
                .eq(StorageInfo::getCommodityCode, commodityCode);
        Integer result =  storageMapper.update(updateWrapper);
        return result==1;
    }
}
